<template>
  <el-dialog v-model="isShowDialog"
             :before-close="handleClose"
             :title="title"
             draggable
             width="80%"
             append-to-body
  >

    <el-form :inline="true" :model="saveParams" :disabled="isView" ref="formRef" label-width="100px" :rules="rules">
      <div style="display: flex;flex-wrap: wrap">
        <el-col :span="6">
          <el-form-item label="入库单号" prop="receiptCode">
            <el-input v-model="saveParams.receiptCode" @input="saveParams.receiptCode=limitCharAndNumber(saveParams.receiptCode)" placeholder="入库单号" clearable/>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select
                :disabled="saveParams.receiptId"
                clearable
                v-model="saveParams.warehouseId"
                @change="changeWarehouse"
            >
              <template v-for="(item,index) in warehouseList" :key="index">
                <el-option :label="item.warehouseName" :value="item.warehouseId"></el-option>
              </template>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="供应商名称">
            <el-select v-model="saveParams.vendorId" clearable placeholder="供应商名称">
              <el-option
                  v-for="item in vendorList"
                  :key="item.vendorId"
                  :label="item.vendorName"
                  :value="item.vendorId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商编码">
            <el-input v-model="saveParams.vendorCode" placeholder="自动填入" clearable disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" style="width: 92%">
            <el-input type="textarea" :rows="3" v-model="saveParams.remark" placeholder="备注" clearable/>
          </el-form-item>
        </el-col>
      </div>

    </el-form>

    <div class="justify-content items-center" style="margin-bottom: 15px">
      <div class="plan">
        <span class="information"></span>
        <span class="informationText">商品信息</span>
      </div>
    </div>
    <div v-if="!isView">
      <el-button type="primary" @click="handleAdd">添加商品</el-button>
      <el-button icon="Delete" type="danger" @click="handleDel">删除所选</el-button>
    </div>
    <vxe-table
        ref="tableRef"
        border
        style="margin-top: 10px;"
        align="center"
        :data="tableList"
        height="300"
        :checkbox-config="{ trigger:'row'}"
        :row-config="{isCurrent: true, isHover: true}"
        :edit-rules="validRules"
        show-footer
        :footer-method="footerMethod"
    >
      <vxe-column type="checkbox" width="80"></vxe-column>
      <vxe-column type="seq" width="80" title="序号"></vxe-column>
      <vxe-column field="skuCode" title="SKU编号"></vxe-column>
      <vxe-column field="skuName" title="商品名称"></vxe-column>
      <vxe-column field="coverUrl"  width="180" title="商品图片">
        <template #default="{row}">
          <ImagePreview v-if="row.coverUrl" :width="150" :height="50" :src="row.coverUrl" ></ImagePreview>
        </template>
      </vxe-column>
      <vxe-column field="totalNum" width="120" title="入库数量">
        <template #header>
          <span style="color: red;">*</span>入库数量
        </template>
        <template #default="{row}">
          <el-input v-model="row.totalNum" @change="countTotal(row)" :disabled="isView"
                    @input="row.totalNum=limitIntNumber(row.totalNum)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="receiptPrice" width="120" title="入库单价">
        <template #header>
          <span style="color: red;">*</span>入库单价
        </template>
        <template #default="{row}">
          <el-input v-model="row.receiptPrice" @change="countTotal(row)" :disabled="isView"
                    @input="row.receiptPrice=limitNumber(row.receiptPrice)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="totalReceiptMoney" width="120" title="入库总额">
        <template #header>
          <span style="color: red;">*</span>入库总额
        </template>
        <template #default="{row}">
          <el-input v-model="row.totalReceiptMoney" @change="contPice(row)" :disabled="isView"
                    @input="row.totalReceiptMoney=limitNumber(row.totalReceiptMoney)" clearable/>
        </template>
      </vxe-column>
      <vxe-column field="unitType" title="单位"></vxe-column>
      <vxe-column field="barcode" title="条码"></vxe-column>
      <vxe-column fixed="right" title="操作" v-if="!isView">
        <template #default="{row}">
          <el-button type="text">删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="clickSave"> 保存 </el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
    </template>

    <SelB2bInstorageGoods v-if="isShowAddGoods" :isShowAddGoods="isShowAddGoods"
                          :companyId="sysUserInfo.companyId"
                          :warehouseId="saveParams.warehouseId"
                          :filterData="tableList"
                          @closeSelDialog="closeSelDialog"></SelB2bInstorageGoods>
  </el-dialog>

</template>

<script setup>
import SelB2bInstorageGoods from "@/views/inStorage/b2bInStorage/component/selB2bInstorageGoods.vue";
import {getCurrentInstance, onMounted, ref} from "vue";
import {b2bReceiptSave, getVendorFilter, warehouseGetFilter} from "@/api/scApi";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {limitCharAndNumber} from "@/utils/shuangcheng";
import {getCompanySelect, getWarehouseSelect} from "@/api/system/user";
import SelB2bPurchaseCommodity from "@/views/procure/B2bPurchase/componet/selB2bPurchaseCommodity.vue";

const {proxy} = getCurrentInstance()
let saveParams = ref({})
const validRules = ref({
  totalNum: [
    {required: true, message: '入库数量不能为空'},
  ],
  receiptPrice: [
    {required: true, message: '入库单价不能为空'},
  ],
  totalReceiptMoney: [
    {required: true, message: '入库总额不能为空'},
  ],
})
// 表单校验
const rules = ref({
  warehouseId: [{required: true, message: "请选择仓库", trigger: "blur"}],
});
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false
  },
  title: {type: String},
  isView: {type: Boolean},
  detailData: {type: Object},
})
const emits = defineEmits(['cancel'])
function handleClose() {
  emits('cancel')
}
let tableList = ref([])
let isShowAddGoods = ref(false)
function handleAdd() {
  if(  !saveParams.value.warehouseId  ){
    proxy.$modal.msgWarning("请先选择公司和仓库!")
    return
  }
  isShowAddGoods.value = true
}


onMounted(() => {

  if (JSON.stringify(props.detailData) != '{}') {
    saveParams.value = props.detailData.header
    tableList.value = props.detailData.details
  }
  getWarehouse()
  if(saveParams.value.receiptId){
    getVendorList()
  }
})
//计算总额
function countTotal(row) {
  if (row.totalNum && row.receiptPrice) {
    row.totalReceiptMoney = (row.totalNum * row.receiptPrice).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}
//计算单价
function contPice(row) {
  if (row.totalReceiptMoney && row.totalNum) {
    row.receiptPrice = (row.totalReceiptMoney / row.totalNum).toFixed(2)
  }
  proxy.$refs.tableRef.updateFooter()
}
function closeSelDialog(data) {
  isShowAddGoods.value = false
  if (data) {
    tableList.value = [...tableList.value, ...data]
  }
}
//删除所选
function handleDel() {
  let selRows = proxy.$refs.tableRef.getCheckboxRecords()
  let a = tableList.value
  let filtered = a.filter(obj => !selRows.some(bObj => bObj.skuId === obj.skuId));
  tableList.value = filtered
}
async function clickSave(){
  if(tableList.value.length===0){
    proxy.$modal.msgWarning("请先添加商品！")
    return
  }
  let params={
    details:tableList.value,
    header:saveParams.value
  }
  const $table = proxy.$refs.tableRef

  if ($table) {
    const errMap = await $table.validate(true)
    if (errMap) {
      console.log('校验失败！')
    } else {
      console.log('校验成功！')
      proxy.$refs.formRef.validate((valid, fileds) => {
        if(valid){
          b2bReceiptSave(params).then(res=>{
            if(res.code===200){
              proxy.$modal.msgSuccess('保存成功')
              emits('cancel', true)
            }
          })
        }
      })
    }
  }

}
function footerMethod({ columns, data }){
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '合计'
      }
      if (['totalNum','totalReceiptMoney'].includes(column.field)) {
        return sumNum(data, column.field)
      }
      return null
    })
  ]
}
const sumNum = (list,field) => {
  let count = 0
  list.forEach(item => {
    if(item[field]){
      count += Number(item[field])
    }
  })
  return count.toFixed(2)
}
const sysUserInfo=JSON.parse(localStorage.getItem("userInfo"))
//获取仓库
let warehouseList = ref([])
function getWarehouse(){
  getWarehouseSelect({'companyId': sysUserInfo.companyId}).then(res => {
    warehouseList.value = res.data
  })
}
function changeWarehouse(){
  saveParams.value.vendorId=''
  vendorList.value=[]
  tableList.value=[]
  getVendorList()
}



//获取供应商下拉
let vendorList = ref([])
function getVendorList() {
  getVendorFilter({}).then(res => {
    if (res.code === 200) {
      vendorList.value = res.data.map(item => {
        item.value = item.id
        item.label = item.name
        return item
      })
    }
  })
}
</script>

<style scoped lang="scss">

</style>